
#include <signal.h>

#include <iostream>

using std::cout;
using std::endl;

#include <workflow/WFFacilities.h>
#include <workflow/HttpMessage.h>
#include <workflow/HttpUtil.h>

static WFFacilities::WaitGroup waitGroup(1);

void sighandler(int num)
{
    printf("sig number %d is comming\n", num);
    waitGroup.done();
}

void parallelCallback(const ParallelWork * )
{
    cout << "parallelCallback is running" << endl;
}

void parallelSeriesCallback(const SeriesWork *) 
{
    cout << ">> parallelSeriesCallback is running" << endl;
    waitGroup.done();
}

void httpCallback(WFHttpTask * );

void test0()
{
    signal(SIGINT, sighandler);

    auto parallelWork = Workflow::create_parallel_work(parallelCallback);

    std::vector<std::string> webs {
        "http://localhost",
        "http://localhost:8081",
        "http://localhost:8082"
    };

    for(size_t i = 0; i < webs.size(); ++i) {
        //创建任务
        auto httpTask = WFTaskFactory::create_http_task(webs[i], 1, 1, httpCallback);
        auto req = httpTask->get_req();
        req->add_header_pair("User-Agent", "Workflow http client");
        req->add_header_pair("Accept", "*/*");
        //创建一个序列
        auto series = Workflow::create_series_work(httpTask, nullptr);
        //将序列放入到并行任务中
        parallelWork->add_series(series);
    }
    //将并行任务放入一个序列中，开始运行
    Workflow::start_series_work(parallelWork, parallelSeriesCallback);


    waitGroup.wait();
}


int main()
{
    test0();
    return 0;
}

void httpCallback(WFHttpTask * httptask)
{
    //当回调函数被运行时，已经完成了数据的接收和发送了
    cout << "httpCallback is running" << endl;
    //1. 错误检测
    int state = httptask->get_state();
    int error = httptask->get_error();

    switch(state) {
    case WFT_STATE_SYS_ERROR:
        printf("system error: %s\n", strerror(error)); break;
    case WFT_STATE_DNS_ERROR:
        printf("dns error: %s\n", gai_strerror(error)); break;
    case WFT_STATE_SUCCESS:
        break;
    }

    if(state != WFT_STATE_SUCCESS) {
        printf("error occurs!\n");
        return;
    }

    printf("task success\n");

    //2.获取请求报文的信息
    //2.1起始行
    auto req = httptask->get_req();
    printf("%s %s %s\n", req->get_method(),
           req->get_request_uri(),
           req->get_http_version());

#if 1
    //2.2首部字段,需要通过一个迭代器进行遍历
    protocol::HttpHeaderCursor cursor(req);
    std::string key, value;
    while(cursor.next(key, value)) {
        cout << key << ": " << value << endl;
    }
    cout << endl;
#endif

    //3. 获取响应报文的信息
    auto resp = httptask->get_resp();
    //3.1 起始行
    printf("%s %s %s\n",resp->get_http_version(),
           resp->get_status_code(),
           resp->get_reason_phrase());

#if 0
    //3.2 首部字段
    protocol::HttpHeaderCursor cursor2(resp);
    while(cursor2.next(key, value)) {
        cout << key << ": " << value << endl;
    }

    //3.3 消息体
    const void * body = nullptr;
    size_t sz = 0;
    resp->get_parsed_body(&body, &sz);
    printf("%s\n", (const char *)body);
#endif

}
